package com.lixixi.tingshu.search;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class AsyncConfig {
	@Bean
	ThreadPoolTaskExecutor threadPoolTaskExecutor() {
		ThreadPoolTaskExecutor executorService = new ThreadPoolTaskExecutor();
		//核心线程数
		executorService.setCorePoolSize(20);
		//最大线程数
		executorService.setMaxPoolSize(30);
		//多余线程存活时间 1h
		executorService.setKeepAliveSeconds(60 * 60);
		//设置线程队列长度
		executorService.setQueueCapacity(200);
		//超过线程数的处理策略
		executorService.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		//设置线程装饰器
		executorService.setTaskDecorator(new WebContextDecorator());
		return executorService;
	}

	class WebContextDecorator implements TaskDecorator {
		@Override
		public Runnable decorate(Runnable runnable) {
			ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
			return () -> {
				try
				{
					RequestContextHolder.setRequestAttributes(requestAttributes);
					runnable.run();
				} finally
				{
					RequestContextHolder.resetRequestAttributes();
				}
			};
		}
	}

}
